<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>教学管理信息服务平台</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    body {
      font-family: 'Microsoft YaHei', Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f5f5f5;
      color: #333;
    }

    .header {
      background-color: #0078d7;
      color: white;
      padding: 10px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .logo {
      display: flex;
      align-items: center;
    }

    .logo img {
      margin-right: 10px;
      width: 32px;
      height: 32px;
    }

    .logo-text {
      font-size: 22px;
      font-weight: normal;
    }

    .user-controls {
      display: flex;
      align-items: center;
    }

    .lang-selector {
      margin-right: 15px;
    }

    .lang-btn {
      background-color: white;
      border: none;
      padding: 5px 10px;
      border-radius: 3px;
      cursor: pointer;
    }

    .avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      background-color: #ddd;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
    }

    .avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .nav-bar {
      background-color: #f0f0f0;
      padding: 0 20px;
      border-bottom: 1px solid #ddd;
    }

    .nav-menu {
      list-style-type: none;
      margin: 0;
      padding: 0;
      display: flex;
    }

    .nav-menu li {
      position: relative;
    }

    .nav-menu a {
      display: block;
      padding: 15px;
      text-decoration: none;
      color: #333;
      transition: background-color 0.3s;
    }

    .nav-menu a:hover {
      background-color: #e0e0e0;
    }

    .dropdown::after {
      content: '▼';
      font-size: 10px;
      margin-left: 5px;
      color: #666;
    }

    /* 添加下拉菜单样式 */
    .submenu {
      display: none;
      position: absolute;
      background-color: white;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
      z-index: 1;
      border-radius: 3px;
      padding: 5px 0;
    }

    .submenu a {
      padding: 10px 15px;
      display: block;
      color: #333;
      text-decoration: none;
    }

    .submenu a:hover {
      background-color: #f5f5f5;
    }

    .nav-menu li:hover .submenu {
      display: block;
    }

    .main-container {
      display: flex;
      padding: 20px;
      gap: 20px;
    }

    .sidebar {
      width: 200px;
      background-color: white;
      border-radius: 5px;
      padding: 15px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .sidebar-title {
      margin: 0 0 15px 0;
      font-size: 16px;
      color: #333;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .sidebar-title .gear-icon {
      color: #aaa;
      cursor: pointer;
    }

    .content {
      flex: 1;
    }

    .student-profile {
      display: flex;
      background-color: white;
      border-radius: 5px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .student-avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 20px;
      background-color: #eee;
    }

    .student-avatar img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .student-info h2 {
      margin: 0 0 5px 0;
      font-size: 18px;
    }

    .student-info p {
      margin: 5px 0;
      color: #666;
      font-size: 14px;
    }

    .notification-section,
    .schedule-section,
    .document-section,
    .grade-section {
      background-color: white;
      border-radius: 5px;
      padding: 15px;
      margin-bottom: 20px;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }

    .section-title {
      margin: 0;
      font-size: 16px;
      color: #333;
    }

    .view-more {
      color: #0078d7;
      text-decoration: none;
      font-size: 14px;
    }

    .notification-list {
      list-style-type: none;
      padding: 0;
      margin: 0;
    }

    .notification-item {
      padding: 8px 0;
      border-bottom: 1px solid #f0f0f0;
    }

    .notification-item:last-child {
      border-bottom: none;
    }

    .notification-title {
      display: flex;
      align-items: center;
      margin-bottom: 3px;
    }

    .important-tag {
      color: #e74c3c;
      margin-right: 5px;
    }

    .new-tag {
      background-color: #2ecc71;
      color: white;
      padding: 1px 5px;
      border-radius: 3px;
      font-size: 12px;
      margin-left: 10px;
    }

    .notification-date {
      margin-left: auto;
      color: #999;
      font-size: 12px;
    }

    .class-schedule {
      width: 100%;
      border-collapse: collapse;
      font-size: 13px;
    }

    .class-schedule th,
    .class-schedule td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: center;
    }

    .class-schedule th {
      background-color: #f9f9f9;
    }

    .document-list,
    .grade-list {
      list-style-type: none;
      padding: 0;
      margin: 0;
    }

    .document-item,
    .grade-item {
      display: flex;
      justify-content: space-between;
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;
    }

    .document-item:last-child,
    .grade-item:last-child {
      border-bottom: none;
    }

    .document-title,
    .grade-course {
      display: flex;
      align-items: center;
    }

    .document-icon,
    .warning-icon {
      color: #e74c3c;
      margin-right: 5px;
    }

    .document-date,
    .grade-score {
      color: #666;
      font-size: 14px;
    }

    .class-schedule td {
      padding: 12px 8px;
      text-align: left;
      border-bottom: 1px solid #eee;
    }

    .class-schedule tr:hover {
      background-color: #f5f5f5;
    }

    .class-info {
      text-align: left;
      display: block;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }

    @media (max-width: 768px) {
      .main-container {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        margin-bottom: 20px;
      }
    }

    .student-info-section {
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      padding: 32px 24px 24px 24px;
      margin-top: 32px;
      max-width: 700px;
      margin-left: auto;
      margin-right: auto;
    }

    #studentInfoForm {
      display: flex;
      flex-wrap: wrap;
      gap: 24px 32px;
    }

    #studentInfoForm>div {
      flex: 1 1 280px;
      min-width: 220px;
      display: flex;
      flex-direction: column;
    }

    #studentInfoForm label {
      font-weight: 500;
      margin-bottom: 6px;
      color: #333;
    }

    #studentInfoForm input,
    #studentInfoForm select {
      padding: 10px 12px;
      border: 1px solid #d0d7de;
      border-radius: 5px;
      font-size: 15px;
      background: #f9f9f9;
      transition: border-color 0.2s;
    }

    #studentInfoForm input:focus,
    #studentInfoForm select:focus {
      border-color: #0078d7;
      outline: none;
      background: #fff;
    }

    #studentInfoForm button[type='submit'] {
      margin-top: 24px;
      width: 100%;
      padding: 12px 0;
      background: #0078d7;
      color: #fff;
      border: none;
      border-radius: 5px;
      font-size: 16px;
      font-weight: bold;
      cursor: pointer;
      transition: background 0.2s;
    }

    #studentInfoForm button[type='submit']:hover {
      background: #005fa3;
    }

    .custom-history-table th,
    .custom-history-table td {
      border: 1px solid #d0d7de;
      padding: 10px 8px;
      text-align: center;
    }

    .custom-history-table th {
      background: #f8fafc;
      color: #333;
      font-weight: 500;
    }

    .custom-history-table tr:nth-child(even) {
      background: #f6f8fa;
    }

    .custom-history-table tr:hover {
      background: #eaf4ff;
    }

    .custom-history-table .cancel-btn {
      background: #fff0f0;
      color: #e74c3c;
      border: 1px solid #e74c3c;
      border-radius: 4px;
      padding: 4px 10px;
      cursor: pointer;
      font-size: 14px;
      transition: background 0.2s, color 0.2s;
    }

    .custom-history-table .cancel-btn:hover {
      background: #e74c3c;
      color: #fff;
    }

    /* 选课模块样式 */
    .course-selection-section {
      padding: 20px;
    }

    .selected-courses-title {
      color: #1890ff;
      font-size: 24px;
      font-weight: 600;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #1890ff;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .search-box {
      display: flex;
      gap: 10px;
    }

    .search-box input {
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      width: 200px;
    }

    .search-box button {
      padding: 8px 16px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    .search-box button:first-of-type {
      background-color: #1890ff;
      color: white;
    }

    .search-box button:last-of-type {
      background-color: #f0f0f0;
      color: #666;
    }

    .course-filters {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;
    }

    .course-filters select {
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      min-width: 120px;
    }

    .course-table,
    .selected-course-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 30px;
    }

    .course-table th,
    .course-table td,
    .selected-course-table th,
    .selected-course-table td {
      padding: 12px;
      text-align: left;
      border-bottom: 1px solid #ddd;
    }

    .course-table th,
    .selected-course-table th {
      background-color: #f5f5f5;
      font-weight: 600;
    }

    .action-btn {
      padding: 6px 12px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }

    .select-course-btn {
      background-color: #52c41a;
      color: white;
    }

    .drop-course-btn {
      background-color: #ff4d4f;
      color: white;
    }

    .selected-courses h3 {
      margin-bottom: 15px;
      color: #333;
    }

    /* 响应式设计 */
    @media screen and (max-width: 768px) {
      .section-header {
        flex-direction: column;
        gap: 15px;
      }

      .search-box {
        width: 100%;
      }

      .search-box input {
        width: 100%;
      }

      .course-filters {
        flex-direction: column;
      }

      .course-table,
      .selected-course-table {
        display: block;
        overflow-x: auto;
      }
    }
  </style>
</head>

<body>
  <!-- 顶部导航栏 -->
  <div class="header">
    <div class="logo">
      <h1 class="logo-text">教学管理信息服务平台</h1>
    </div>
    <div class="user-controls">
      <div class="lang-selector">
        <button class="lang-btn">中文 ▼</button>
      </div>
      <div class="avatar">
        <!-- 删除图片内容 -->
      </div>
    </div>
  </div>

  <!-- 二级导航栏 -->
  <nav class="nav-bar">
    <ul class="nav-menu">
      <li><a href="#" class="dropdown">报名申请</a></li>
      <li>
        <a href="#" class="dropdown">信息维护</a>
        <div class="submenu">
          <a href="#personal-info-edit">学生个人信息维护</a>
        </div>
      </li>
      <li><a href="#" id="course-selection-menu" class="dropdown">选课</a>
        <div class="submenu">
          <a href="#course-select" id="menu-course-select">选课</a>
          <a href="#selected-courses" id="menu-selected-courses">已选课程</a>
        </div>
      </li>
      <li>
        <a href="#" class="dropdown">信息查询</a>
        <div class="submenu">
          <a href="#" id="profile-link">查询个人信息</a>
          <a href="schedule.html" id="schedule-link">个人课表查询</a>
          <a href="#grade-info">学生成绩查询</a>
          <a href="#exam-info">考试信息查询</a>
        </div>
      </li>
      <li><a href="#" class="dropdown">教学评价</a></li>
      <li><a href="#" class="dropdown">毕业设计(论文)</a></li>
    </ul>
  </nav>

  <!-- 主内容区 -->
  <div class="main-container">
    <!-- 左侧边栏 -->
    <div class="sidebar">
      <h2 class="sidebar-title">
        我的应用
        <span class="gear-icon">⚙</span>
      </h2>
      <!-- 这里可以添加更多侧边栏内容 -->
    </div>

    <!-- 主内容 -->
    <div class="content">
      <!-- 学生个人信息 -->
      <div class="student-profile">
        <div class="student-avatar">
          <img src="" alt="学生头像">
        </div>
        <div class="student-info">
          <h2>学生</h2>
          <p></p>
        </div>
      </div>

      <!-- 学生个人信息维护 -->
      <div class="personal-info-edit-section" style="display: none;">
        <div class="section-header">
          <h3 class="section-title">学生个人信息维护</h3>
        </div>
        <div style="background-color: white; padding: 20px; border-radius: 5px; margin-top: 15px;">
          <div style="display: flex; justify-content: flex-end; margin-bottom: 15px;">
            <button id="apply-btn"
              style="padding: 8px 15px; border: none; background-color: #0078d7; color: white; border-radius: 3px; margin-right: 5px; cursor: pointer;">
              <span style="margin-right: 5px;">+</span>申请
            </button>
            <button id="withdraw-btn"
              style="padding: 8px 15px; border: none; background-color: white; color: #333; border: 1px solid #ccc; border-radius: 3px; cursor: pointer;">
              <span style="margin-right: 5px;"><img src="" alt="" style="width: 14px; height: 14px;"></span>撤销申请
            </button>
          </div>

          <div class="history-records" style="margin-bottom: 20px;">
            <h4 style="margin-bottom: 10px; font-size: 16px; font-weight: normal;">历史修改记录</h4>
            <table class="custom-history-table" style="width: 100%; border-collapse: collapse; font-size: 15px;">
              <thead>
                <tr style="background-color: #f5f5f5;">
                  <th style="padding: 10px; text-align: center; border: 1px solid #ddd;">学号</th>
                  <th style="padding: 10px; text-align: center; border: 1px solid #ddd;">申请状态</th>
                  <th style="padding: 10px; text-align: center; border: 1px solid #ddd;">申请时间</th>
                  <th style="padding: 10px; text-align: center; border: 1px solid #ddd;">撤销</th>
                </tr>
              </thead>
              <tbody>
                <!-- 这里由JS动态填充 -->
              </tbody>
            </table>
          </div>
        </div>

        <!-- 通知区域 -->
        <div class="notification-section">
          <div class="section-header">
            <h3 class="section-title">通知</h3>
            <a href="#" class="view-more">更多</a>
          </div>
          <ul class="notification-list">
            <!-- 内容已清空 -->
          </ul>
        </div>

        <!-- 课表区域 -->
        <div class="schedule-section">
          <div class="section-header">
            <h3 class="section-title">课表</h3>
            <a href="#" class="view-more">更多</a>
          </div>
          <table class="class-schedule">
            <tr>
              <th>课程</th>
              <th>时间</th>
              <th>地点</th>
            </tr>
            <!-- 内容已清空 -->
          </table>
          <div style="text-align: center; margin-top: 10px;">
            <a href="#" class="view-more" style="margin-right: auto;">更多</a>
          </div>
        </div>

        <!-- 文件区域 -->
        <div class="document-section">
          <div class="section-header">
            <h3 class="section-title">文件</h3>
            <a href="#" class="view-more">更多</a>
          </div>
          <ul class="document-list">
            <!-- 内容已清空 -->
          </ul>
        </div>

        <!-- 成绩考试区域 -->
        <div class="grade-section">
          <div class="section-header">
            <h3 class="section-title">成绩</h3>
            <a href="#" class="view-more">更多</a>
          </div>
          <ul class="grade-list">
            <!-- 内容已清空 -->
          </ul>
        </div>

        <!-- 消息区域 -->
        <div class="grade-section">
          <div class="section-header">
            <h3 class="section-title">消息</h3>
            <a href="#" class="view-more">更多</a>
          </div>
          <ul class="grade-list">
            <!-- 内容已清空 -->
          </ul>
        </div>
      </div>

      <!-- 选课模块 -->
      <div class="course-selection-section" id="course-select-section" style="display: none;">
        <div class="section-header">
          <h2 class="selected-courses-title">选课系统</h2>
          <div class="search-box">
            <input type="text" id="courseSearchInput" placeholder="搜索课程名称">
            <button id="searchCourseBtn">搜索</button>
            <button id="resetSearchBtn">重置</button>
          </div>
        </div>
        <div class="course-filters">
          <select id="courseTypeFilter">
            <option value="">全部类型</option>
            <option value="必修">必修</option>
            <option value="选修">选修</option>
          </select>
          <select id="weekdayFilter">
            <option value="">全部时间</option>
            <option value="周一">周一</option>
            <option value="周二">周二</option>
            <option value="周三">周三</option>
            <option value="周四">周四</option>
            <option value="周五">周五</option>
            <option value="周六">周六</option>
            <option value="周日">周日</option>
          </select>
        </div>
        <div class="course-list">
          <table class="course-table">
            <thead>
              <tr>
                <th>课程名称</th>
                <th>课程类型</th>
                <th>授课教师</th>
                <th>学分</th>
                <th>上课时间</th>
                <th>上课地点</th>
                <th>已选人数</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="courseTableBody">
              <!-- 课程列表将通过JavaScript动态填充 -->
            </tbody>
          </table>
        </div>
      </div>

      <div class="course-selection-section" id="selected-courses-section" style="display: none;">
        <h2 class="selected-courses-title">已选课程</h2>
        <table class="selected-course-table">
          <thead>
            <tr>
              <th>课程名称</th>
              <th>课程类型</th>
              <th>授课教师</th>
              <th>学分</th>
              <th>上课时间</th>
              <th>上课地点</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="selectedCourseTableBody">
            <!-- 已选课程列表将通过JavaScript动态填充 -->
          </tbody>
        </table>
      </div>
    </div>

    <!-- Bootstrap 模态框 -->
    <div class="modal fade" id="infoModal" tabindex="-1" role="dialog" aria-labelledby="infoModalLabel"
      aria-hidden="true">
      <div class="modal-dialog" style="max-width: 900px;">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title" id="infoModalLabel" style="color:#0078d7;">基本信息修改申请</h4>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="font-size: 28px;">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form id="studentInfoForm">
              <div>
                <label for="student-id">学号</label>
                <input type="text" id="student-id" name="student_id" required>
              </div>
              <div>
                <label for="name">姓名</label>
                <input type="text" id="name" name="name" required>
              </div>
              <div>
                <label for="id-type">证件类型</label>
                <select id="id-type" name="id_type">
                  <option value="居民身份证">居民身份证</option>
                  <option value="护照">护照</option>
                  <option value="其他">其他</option>
                </select>
              </div>
              <div>
                <label for="id-number">证件号码</label>
                <input type="text" id="id-number" name="id_number">
              </div>
              <div>
                <label for="phone">电话号码</label>
                <input type="text" id="phone" name="phone">
              </div>
              <div>
                <label for="native-place">籍贯</label>
                <input type="text" id="native-place" name="native_place">
              </div>
              <div>
                <label for="enroll-date">入学日期</label>
                <input type="date" id="enroll-date" name="enroll_date">
              </div>
              <div>
                <label for="ethnicity">民族</label>
                <input type="text" id="ethnicity" name="ethnicity">
              </div>
              <div>
                <label for="blood-type">血型名称</label>
                <select id="blood-type" name="blood_type">
                  <option value="A">A型</option>
                  <option value="B">B型</option>
                  <option value="AB">AB型</option>
                  <option value="O">O型</option>
                </select>
              </div>
              <div>
                <label for="political">政治面貌</label>
                <input type="text" id="political" name="political">
              </div>
              <div>
                <label for="gender">性别</label>
                <select id="gender" name="gender">
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
              <button type="submit">提交</button>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      console.log('学生页面已加载');

      // 检查登录状态和账号审核状态
      const userToken = localStorage.getItem('userToken');

      // 如果没有登录令牌，重定向到登录页面
      if (!userToken) {
        console.log('未找到登录令牌，重定向到登录页面');
        window.location.href = 'index.html';
        return;
      }

      // 验证用户信息并加载数据
      validateUserAndLoadData();

      // 验证用户信息并加载数据
      async function validateUserAndLoadData() {
        console.log('开始验证用户并加载数据...'); // 添加日志
        try {
          const response = await fetch('/api/user/info', {
            headers: {
              'Authorization': `Bearer ${userToken}`
            }
          });

          if (!response.ok) {
            throw new Error('获取用户信息失败');
          }

          const data = await response.json();
          console.log('用户信息验证响应:', data); // 添加日志

          if (!data.success) {
            throw new Error(data.message || '验证失败');
          }

          // 检查用户状态和角色
          if (data.user.status !== 'approved') {
            alert('您的账号尚未通过审核，无法访问学生页面');
            window.location.href = 'index.html';
            return;
          }

          if (data.user.role !== 'student') {
            alert('您不是学生用户，无法访问此页面');
            window.location.href = 'index.html';
            return;
          }

          // 填充用户信息并存储用户ID和学号
          if (data.user.profile) {
            document.querySelector('.student-info h2').textContent = `${data.user.profile.real_name || data.user.username} 学生`;
            document.querySelector('.student-info p').textContent = `${data.user.profile.department || ''} ${data.user.profile.class_name || ''}`;
            localStorage.setItem('user_id', data.user.id); // 存储用户ID (users.id)
            localStorage.setItem('student_id_number', data.user.profile.student_id); // 存储学生学号 (user_profiles.student_id)
            localStorage.setItem('userInfo', JSON.stringify({
              user_id: data.user.id, // 存储用户ID
              student_id_number: data.user.profile.student_id, // 存储学生学号
              real_name: data.user.profile.real_name || data.user.username,
              department: data.user.profile.department,
              class_name: data.user.profile.class_name
            }));
          } else { // 如果没有profile信息，至少存储用户ID
            localStorage.setItem('user_id', data.user.id); // 存储用户ID
            localStorage.setItem('userInfo', JSON.stringify({
              user_id: data.user.id,
              real_name: data.user.username
            }));
          }

          // 加载学生页面数据 (包括课程和已选课程)
          loadStudentData();
          // 在验证成功后立即加载课程列表和已选课程
          await loadAllCourses();
          await loadSelectedCourses();

        } catch (error) {
          console.error('验证用户失败:', error); // 保留原有错误日志
          alert('验证用户身份失败，请重新登录');
          localStorage.removeItem('userToken');
          // 清除存储的用户信息
          localStorage.removeItem('user_id');
          localStorage.removeItem('student_id_number');
          localStorage.removeItem('userInfo');
          window.location.href = 'index.html';
        }
      }

      // 加载学生页面数据
      function loadStudentData() {
        console.log('加载学生数据 (用户信息验证成功后)'); // 添加日志
        // 这里可以添加加载课表、通知等数据的代码
        // 课程和已选课程已在 validateUserAndLoadData 中加载
      }

      // 处理所有下拉菜单点击事件
      document.querySelectorAll('.submenu a').forEach(link => {
        link.addEventListener('click', function (e) {
          const href = this.getAttribute('href');
          // 只阻止锚点跳转，外部页面正常跳转
          if (href && href.startsWith('#')) {
            e.preventDefault();
            const target = href.substring(1); // 去除 # 符号

            // 隐藏所有内容区域
            const contentSections = document.querySelectorAll('.content > div');
            contentSections.forEach(section => {
              section.style.display = 'none';
            });

            // 根据点击的菜单项显示相应内容
            switch (target) {
              // 信息查询菜单
              case 'personal-info':
                document.querySelector('.student-profile').style.display = 'flex';
                break;
              case 'schedule-info':
                document.querySelector('.schedule-section').style.display = 'block';
                break;
              case 'grade-info':
                document.querySelector('.grade-section').style.display = 'block';
                break;
              case 'exam-info':
                alert('考试信息暂未开放');
                break;

              // 信息维护菜单
              case 'personal-info-edit':
                const editSection = document.querySelector('.personal-info-edit-section');
                editSection.style.display = 'block';

                // 隐藏其它区域
                editSection.querySelectorAll('.notification-section, .schedule-section, .document-section, .grade-section').forEach(el => {
                  el.style.display = 'none';
                });
                Array.from(editSection.children).forEach(child => {
                  if (
                    child.classList.contains('notification-section') ||
                    child.classList.contains('schedule-section') ||
                    child.classList.contains('document-section') ||
                    child.classList.contains('grade-section')
                  ) {
                    child.style.display = 'none';
                  } else {
                    child.style.display = '';
                  }
                });
                break;

              default:
                contentSections.forEach(section => {
                  if (!section.classList.contains('personal-info-edit-section')) {
                    section.style.display = '';
                  }
                });
            }
          }
          // 否则（如profile.html），让浏览器正常跳转
        });
      });

      // ---- 学生个人信息维护相关代码 ----

      // 申请按钮点击事件
      const applyBtn = document.getElementById('apply-btn');
      if (applyBtn) {
        applyBtn.addEventListener('click', function () {
          $('#infoModal').modal('show');
        });
      }

      // 关闭表单按钮点击事件
      const closeFormBtn = document.getElementById('close-form-btn');
      const cancelBtn = document.getElementById('cancel-btn');
      if (closeFormBtn) {
        closeFormBtn.addEventListener('click', function () {
          $('#infoModal').modal('hide');
        });
      }
      if (cancelBtn) {
        cancelBtn.addEventListener('click', function () {
          $('#infoModal').modal('hide');
        });
      }

      // 处理信息标签页切换
      const tabs = document.querySelectorAll('.info-tabs .tab');
      if (tabs.length > 0) {
        tabs.forEach(tab => {
          tab.addEventListener('click', function () {
            // 移除所有标签的active类
            tabs.forEach(t => t.classList.remove('active'));
            // 添加当前标签的active类
            this.classList.add('active');

            // 获取目标标签页
            const target = this.getAttribute('data-tab');

            // 模拟标签页切换（实际应用中应该显示相应的内容区域）
            if (target !== 'basic') {
              alert(`${target} 标签页功能正在开发中`);
            }
          });
        });
      }

      // 处理保存草稿按钮点击事件
      const saveBtn = document.getElementById('save-btn');
      if (saveBtn) {
        saveBtn.addEventListener('click', function () {
          // 收集表单数据
          const formData = collectFormData();

          console.log('保存草稿:', formData);
          alert('草稿已保存');
        });
      }

      // 处理表单提交事件
      const studentInfoForm = document.getElementById('studentInfoForm');
      if (studentInfoForm) {
        studentInfoForm.addEventListener('submit', async function (e) {
          e.preventDefault();
          const formData = collectFormData();
          if (!formData.student_id) {
            alert('未获取到学号，无法提交申请');
            return;
          }
          try {
            const response = await fetch('/api/info-modification/request', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify(formData)
            });
            const result = await response.json();
            if (result.success) {
              alert('申请已提交');
              $('#infoModal').modal('hide');
              await loadHistoryRecords();
            } else {
              alert(result.message || '提交失败');
            }
          } catch (error) {
            alert('提交失败，请稍后重试');
          }
        });
      }

      // 撤销申请按钮点击事件
      const withdrawBtn = document.getElementById('withdraw-btn');
      if (withdrawBtn) {
        withdrawBtn.addEventListener('click', function () {
          alert('当前没有可撤销的申请');
        });
      }

      // 收集表单数据的辅助函数
      function getInputValue(id) {
        const el = document.getElementById(id);
        return el ? el.value : '';
      }

      function collectFormData() {
        return {
          student_id: getStudentId(),
          name: getInputValue('name'),
          id_type: getInputValue('id-type'),
          id_number: getInputValue('id-number'),
          phone: getInputValue('phone'),
          native_place: getInputValue('native-place'),
          enroll_date: getInputValue('enroll-date'),
          ethnicity: getInputValue('ethnicity'),
          blood_type: getInputValue('blood-type'),
          political: getInputValue('political'),
          gender: getInputValue('gender')
        };
      }

      function translateStatus(status) {
        switch (status) {
          case 'pending': return '待审核';
          case 'approved': return '已批准';
          case 'rejected': return '已拒绝';
          default: return status;
        }
      }

      // 加载历史记录（异步从后端获取）
      async function loadHistoryRecords() {
        const tbody = document.querySelector('.history-records tbody');
        tbody.innerHTML = '<tr><td colspan="4" style="padding: 15px; text-align: center; border: 1px solid #ddd;">加载中...</td></tr>';
        const studentId = getStudentId();
        if (!studentId) {
          tbody.innerHTML = '<tr><td colspan="4" style="padding: 15px; text-align: center; border: 1px solid #ddd;">未获取到学号，无法加载历史记录</td></tr>';
          return;
        }
        try {
          const res = await fetch(`/api/info-modification/history?student_id=${studentId}`);
          const data = await res.json();
          if (data.success && Array.isArray(data.records) && data.records.length > 0) {
            tbody.innerHTML = '';
            data.records.forEach(record => {
              const tr = document.createElement('tr');
              tr.innerHTML = `
                <td>${record.student_id || ''}</td>
                <td>${translateStatus(record.status) || ''}</td>
                <td>${record.created_at ? new Date(record.created_at).toLocaleString() : ''}</td>
                <td>
                  ${record.status === 'pending' ? `<button class="cancel-btn" data-request-id="${record.request_id}">撤销</button>` : ''}
                </td>
              `;
              tbody.appendChild(tr);
            });
            // 绑定撤销按钮事件
            tbody.querySelectorAll('.cancel-btn').forEach(btn => {
              btn.addEventListener('click', async function () {
                const requestId = this.getAttribute('data-request-id');
                if (!requestId) return;
                if (!confirm('确定要撤销该申请吗？')) return;
                const res = await fetch('/api/info-modification/cancel', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ request_id: requestId, student_id: studentId })
                });
                const result = await res.json();
                if (result.success) {
                  alert('撤销成功');
                  loadHistoryRecords();
                } else {
                  alert(result.message || '撤销失败');
                }
              });
            });
          } else {
            tbody.innerHTML = '<tr><td colspan="4" style="padding: 15px; text-align: center; border: 1px solid #ddd;">没有符合条件记录!</td></tr>';
          }
        } catch (err) {
          tbody.innerHTML = '<tr><td colspan="4" style="padding: 15px; text-align: center; border: 1px solid #ddd;">加载失败</td></tr>';
        }
      }

      // 页面加载时自动加载历史记录
      loadHistoryRecords();

      function getStudentId() {
        let studentId = localStorage.getItem('student_id_number');
        if (!studentId) {
          const input = document.getElementById('student-id');
          if (input) studentId = input.value;
        }
        return studentId;
      }

      // 假设你有登录成功后的回调或初始化代码
      function onLoginSuccess(user) {
        // user对象应包含student_id字段
        if (user && user.student_id) {
          localStorage.setItem('userInfo', JSON.stringify(user));
        }
      }

      // 绑定"查询个人信息"菜单点击事件
      const profileLink = document.getElementById('profile-link');
      if (profileLink) {
        profileLink.addEventListener('click', function (e) {
          e.preventDefault();
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
          if (userInfo.student_id_number) {
            window.location.href = `profile.html?student_id=${userInfo.student_id_number}`;
          } else {
            alert('未找到学生信息，请重新登录');
            window.location.href = 'index.html';
          }
        });
      }

      // 选课相关功能
      // 获取选课模块元素
      const courseSelectionSection = document.querySelector('.course-selection-section');
      const courseTableBody = document.getElementById('courseTableBody');
      const selectedCourseTableBody = document.getElementById('selectedCourseTableBody');
      const courseSearchInput = document.getElementById('courseSearchInput');
      const searchCourseBtn = document.getElementById('searchCourseBtn');
      const resetSearchBtn = document.getElementById('resetSearchBtn');
      const courseTypeFilter = document.getElementById('courseTypeFilter');
      const weekdayFilter = document.getElementById('weekdayFilter');

      // 存储课程数据
      let allCourses = [];
      let selectedCourses = [];

      // 加载所有课程
      async function loadAllCourses() {
        console.log('尝试加载所有课程...'); // 添加日志
        try {
          const response = await fetch('/api/courses');
          const data = await response.json();
          console.log('加载所有课程响应:', data); // 添加日志
          if (data.success && Array.isArray(data.courses)) {
            allCourses = data.courses;
            renderCourseTable();
          } else {
            console.error('加载课程失败：后端返回非成功或数据格式错误', data); // 添加错误日志
          }
        } catch (error) {
          console.error('加载课程失败:', error); // 保留原有错误日志
          alert('加载课程失败，请刷新页面重试');
        }
      }

      // 加载已选课程
      async function loadSelectedCourses() {
        console.log('尝试加载已选课程...'); // 添加日志
        try {
          // 从 localStorage 获取用户ID，用于后端查询
          const userId = localStorage.getItem('user_id');
          if (!userId) {
            console.error('未找到用户ID，无法加载已选课程'); // 添加日志
            // alert('请先登录'); // 不在这里弹窗，避免页面加载时打断用户
            return;
          }

          // 使用用户ID作为查询参数
          const response = await fetch(`/api/student/courses?user_id=${userId}`);
          const data = await response.json();
          console.log('加载已选课程响应:', data); // 添加日志
          if (data.success && Array.isArray(data.courses)) {
            selectedCourses = data.courses;
            renderSelectedCourseTable();
          } else {
            console.error('加载已选课程失败：后端返回非成功或数据格式错误', data); // 添加错误日志
            // 即使失败也清空列表并渲染空状态
            selectedCourses = [];
            renderSelectedCourseTable();
          }
        } catch (error) {
          console.error('加载已选课程失败:', error); // 保留原有错误日志
          // alert('加载已选课程失败，请刷新页面重试'); // 不在这里弹窗
          selectedCourses = [];
          renderSelectedCourseTable();
        }
      }

      // 渲染课程表格
      function renderCourseTable() {
        console.log('渲染课程表格，数据量:', allCourses.length); // 添加日志
        if (!courseTableBody) {
          console.error('未找到courseTableBody元素'); // 添加错误日志
          return;
        }

        // 应用筛选
        let filteredCourses = allCourses;
        const searchText = courseSearchInput.value.toLowerCase();
        const selectedType = courseTypeFilter.value; // 确保这些元素存在且获取到正确的值
        const selectedWeekday = weekdayFilter.value;

        console.log('筛选条件:', { searchText, selectedType, selectedWeekday }); // 添加日志

        if (searchText) {
          filteredCourses = filteredCourses.filter(course =>
            course.course_name.toLowerCase().includes(searchText)
          );
        }

        if (selectedType) {
          filteredCourses = filteredCourses.filter(course =>
            course.course_type === selectedType
          );
        }

        if (selectedWeekday) {
          filteredCourses = filteredCourses.filter(course =>
            course.weekday === selectedWeekday
          );
        }

        // 渲染表格
        courseTableBody.innerHTML = ''; // 清空原有内容
        if (filteredCourses.length === 0) {
          courseTableBody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无课程数据或没有匹配的课程</td></tr>'; // 添加无数据提示
          console.log('没有课程需要渲染'); // 添加日志
          return;
        }

        filteredCourses.forEach(course => {
          // 使用 course.current_students 和 course.student_count 来显示已选/可选人数
          const enrolledDisplay = `${course.current_students || 0}/${course.student_count || '-'}`;
          // 检查当前课程是否已被当前用户选择
          const isSelected = selectedCourses.some(sc => sc.id === course.id); // 这里的sc.id应该与course.id比较

          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td>${course.course_name || ''}</td>
            <td>${course.course_type || ''}</td>
            <td>${course.teacher_real_name || course.teacher || ''}</td>
            <td>${course.credit || ''}</td>
            <td>${(course.weekday || '') + ' ' + (course.section || '')}</td>
            <td>${course.classroom || ''}</td>
            <td>${enrolledDisplay}</td> <!-- 显示已选/可选人数 -->
            <td>
              <button class="action-btn ${isSelected ? 'drop-course-btn' : 'select-course-btn'}"
                      onclick="${isSelected ? 'dropCourse' : 'selectCourse'}(${course.id})">
                ${isSelected ? '退课' : '选课'}
              </button>
            </td>
          `;
          courseTableBody.appendChild(tr);
        });
        console.log(`成功渲染 ${filteredCourses.length} 条课程数据`); // 添加日志
      }

      // 渲染已选课程表格
      function renderSelectedCourseTable() {
        console.log('渲染已选课程表格，数据量:', selectedCourses.length); // 添加日志
        if (!selectedCourseTableBody) {
          console.error('未找到selectedCourseTableBody元素'); // 添加错误日志
          return;
        }

        selectedCourseTableBody.innerHTML = ''; // 清空原有内容
        if (selectedCourses.length === 0) {
          selectedCourseTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无已选课程</td></tr>'; // 添加无数据提示
          console.log('没有已选课程需要渲染'); // 添加日志
          return;
        }

        selectedCourses.forEach(course => {
          const tr = document.createElement('tr');
          tr.innerHTML = `
            <td>${course.course_name || ''}</td>
            <td>${course.course_type || ''}</td>
            <td>${course.teacher_real_name || course.teacher || ''}</td>
            <td>${course.credit || ''}</td>
            <td>${(course.weekday || '') + ' ' + (course.section || '')}</td>
            <td>${course.classroom || ''}</td>
            <td>
              <button class="action-btn drop-course-btn" onclick="dropCourse(${course.id})">
                退课
              </button>
            </td>
          `;
          selectedCourseTableBody.appendChild(tr);
        });
        console.log(`成功渲染 ${selectedCourses.length} 条已选课程数据`); // 添加日志
      }

      // 选课函数 - 使用用户ID
      window.selectCourse = async function (courseId) {
        console.log('尝试选课:', courseId); // 添加日志
        try {
          const userId = localStorage.getItem('user_id'); // 从 localStorage 获取用户ID
          if (!userId) {
            alert('请先登录');
            return;
          }

          const response = await fetch('/api/student/courses', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              // 可以选择在这里添加Authorization头，如果后端需要验证用户身份才能选课
              'Authorization': `Bearer ${userToken}`
            },
            body: JSON.stringify({
              student_id: parseInt(userId), // 确保发送的是INTEGER类型的用户ID
              course_id: courseId
            })
          });

          const data = await response.json();
          console.log('选课接口响应:', data); // 添加日志
          if (data.success) {
            alert('选课成功');
            // 选课成功后，需要重新加载所有课程（以便更新按钮状态和已选人数）和已选课程列表
            await loadAllCourses();
            await loadSelectedCourses();
          } else {
            alert(data.message || '选课失败');
          }
        } catch (error) {
          console.error('选课失败:', error); // 保留原有错误日志
          alert('选课失败，请重试');
        }
      };

      // 退课函数 - 使用用户ID
      window.dropCourse = async function (courseId) {
        console.log('尝试退课:', courseId); // 添加日志
        if (!confirm('确定要退选该课程吗？')) {
          return;
        }

        try {
          const userId = localStorage.getItem('user_id'); // 从 localStorage 获取用户ID
          if (!userId) {
            alert('请先登录');
            return;
          }

          const response = await fetch('/api/student/courses', {
            method: 'DELETE',
            headers: {
              'Content-Type': 'application/json',
              // 可以选择在这里添加Authorization头
              'Authorization': `Bearer ${userToken}`
            },
            body: JSON.stringify({
              student_id: parseInt(userId), // 确保发送的是INTEGER类型的用户ID
              course_id: courseId
            })
          });

          const data = await response.json();
          console.log('退课接口响应:', data); // 添加日志
          if (data.success) {
            alert('退课成功');
            // 退课成功后，需要重新加载所有课程（以便更新按钮状态和已选人数）和已选课程列表
            await loadAllCourses();
            await loadSelectedCourses();
          } else {
            alert(data.message || '退课失败');
          }
        } catch (error) {
          console.error('退课失败:', error); // 保留原有错误日志
          alert('退课失败，请重试');
        }
      };

      // 绑定搜索和筛选事件
      if (searchCourseBtn) {
        searchCourseBtn.addEventListener('click', renderCourseTable);
      }

      if (resetSearchBtn) {
        resetSearchBtn.addEventListener('click', function () {
          courseSearchInput.value = '';
          courseTypeFilter.value = '';
          weekdayFilter.value = '';
          renderCourseTable();
        });
      }

      if (courseTypeFilter) {
        courseTypeFilter.addEventListener('change', renderCourseTable);
      }

      if (weekdayFilter) {
        weekdayFilter.addEventListener('change', renderCourseTable);
      }

      // 初始化加载数据 - 在DOM完全加载后立即调用
      loadAllCourses();
      loadSelectedCourses();

      // 绑定二级菜单点击事件
      const menuCourseSelect = document.getElementById('menu-course-select');
      const menuSelectedCourses = document.getElementById('menu-selected-courses');
      const courseSelectSection = document.getElementById('course-select-section');
      const selectedCoursesSection = document.getElementById('selected-courses-section');

      if (menuCourseSelect && menuSelectedCourses && courseSelectSection && selectedCoursesSection) {
        menuCourseSelect.addEventListener('click', async function (e) { // 将处理函数改为 async
          e.preventDefault();

          // 隐藏所有内容区域
          const contentSections = document.querySelectorAll('.content > div');
          contentSections.forEach(section => {
            section.style.display = 'none';
          });

          courseSelectSection.style.display = 'block';
          selectedCoursesSection.style.display = 'none';
          // 重新加载课程数据和已选课程数据
          await loadAllCourses(); // 确保加载完成
          await loadSelectedCourses(); // 确保加载完成
        });
        menuSelectedCourses.addEventListener('click', async function (e) { // 将处理函数改为 async
          e.preventDefault();

          // 隐藏所有内容区域
          const contentSections = document.querySelectorAll('.content > div');
          contentSections.forEach(section => {
            section.style.display = 'none';
          });

          courseSelectSection.style.display = 'none';
          selectedCoursesSection.style.display = 'block';
          // 重新加载已选课程数据和所有课程数据
          await loadAllCourses(); // 确保加载完成
          await loadSelectedCourses(); // 确保加载完成
        });
      }
      // 默认显示选课页面
      // 在 DOMContentLoaded 外部设置初始显示，避免重复设置
      // if (courseSelectSection && selectedCoursesSection) {
      //   courseSelectSection.style.display = 'block';
      //   selectedCoursesSection.style.display = 'none';
      // }
    }); // 外部 DOMContentLoaded 结束

    // 在 DOMContentLoaded 外部设置初始显示
    const courseSelectSection = document.getElementById('course-select-section');
    const selectedCoursesSection = document.getElementById('selected-courses-section');
    const studentProfileSection = document.querySelector('.student-profile'); // 获取个人信息部分
    const personalInfoEditSection = document.querySelector('.personal-info-edit-section'); // 获取信息维护部分
    // 获取其他内容区域，例如通知、课表等
    const otherContentSections = document.querySelectorAll('.content > div:not(.course-selection-section):not(.student-profile):not(.personal-info-edit-section)');

    // 页面加载完成后，默认显示个人信息部分，隐藏其他部分
    document.addEventListener('DOMContentLoaded', function () {
      if (studentProfileSection) studentProfileSection.style.display = 'flex';
      if (courseSelectSection) courseSelectSection.style.display = 'none';
      if (selectedCoursesSection) selectedCoursesSection.style.display = 'none';
      if (personalInfoEditSection) personalInfoEditSection.style.display = 'none';
      otherContentSections.forEach(section => { // 隐藏其他所有内容区域
        section.style.display = 'none';
      });
    });

  </script>
</body>

</html>